import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:portal_website/home_page.dart';
import 'package:portal_website/main_controller.dart';
import 'package:portal_website/pages/double_page.dart';
import 'package:portal_website/pages/empowerment_platform.dart';
import 'package:portal_website/pages/leadership_care.dart';
import 'package:portal_website/pages/news.dart';
import 'package:portal_website/pages/service_capability.dart';
import 'package:portal_website/tool/color_util.dart';

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage>
    with SingleTickerProviderStateMixin {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  late MainController controller;
  @override
  Widget build(BuildContext context) {
    return GetBuilder<MainController>(
        init: MainController(),
        builder: (logic) {
          controller = logic;
          return Container(
            color: ColorsUtil.COLOR_BACKGROUND,
            padding: EdgeInsets.only(left: 20, right: 20, top: 20, bottom: 20),
            child: Scaffold(
              appBar: PreferredSize(
                  preferredSize: Size(Get.width, 80),
                  child: _buildFixedAppBar()),
              body: Stack(
                children: [
                  Positioned.fill(
                    child: IndexedStack(
                      index: logic.currentIndex,
                      children: logic.contentPages,
                    ),
                  ),
                  // 右侧菜单
                  if (controller.showRightMenu)
                    AnimatedPositioned(
                      duration: Duration(milliseconds: 300),
                      curve: Curves.easeOut,
                      top: 0,
                      right: 0,
                      left: 0,
                      child: MouseRegion(
                        onEnter: (_) {
                          controller.showRightMenu = true;
                          setState(() {});
                        },
                        onExit: (_) {
                          controller.showRightMenu = false;
                          setState(() {});
                        },
                        onHover: (_) {
                          controller.showRightMenu = true;
                          setState(() {});
                        },
                        child: Container(
                          height: 500,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black26,
                                blurRadius: 10,
                                offset: Offset(-4, 0),
                              ),
                            ],
                          ),
                          // padding: EdgeInsets.only(
                          //   top: 30,
                          // ),
                          child: GridView.builder(
                            scrollDirection: Axis.horizontal,
                            padding: EdgeInsets.only(
                                left: 50, right: 50, bottom: 30),
                            shrinkWrap: true,
                            gridDelegate:
                                SliverGridDelegateWithMaxCrossAxisExtent(
                                    maxCrossAxisExtent: 40,
                                    mainAxisExtent: 100,
                                    mainAxisSpacing: 10,
                                    crossAxisSpacing: 10),
                            itemBuilder: (context, index) {
                              SubMenuItem subItem = controller
                                  .navbarItems[controller.currentMenuIndex]
                                  .subItems![index];
                              return GestureDetector(
                                onTap: () {
                                  controller.currentIndex = subItem.index;
                                  controller.showRightMenu = false;
                                  controller.currentNavIndex = 1;
                                  controller.currentSubIndex = index;
                                  controller.update();
                                },
                                child: Container(
                                  color: controller.currentSubIndex == index
                                      ? ColorsUtil.color3280FC
                                      : Colors.transparent,
                                  alignment: Alignment.center,
                                  child: Text(
                                    subItem.title,
                                    style: TextStyle(
                                        color:
                                            controller.currentSubIndex == index
                                                ? Colors.white
                                                : Colors.black),
                                  ),
                                ),
                              );
                            },
                            itemCount: controller
                                .navbarItems[controller.currentMenuIndex]
                                .subItems
                                ?.length,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ),
          );
        });
  }

  Widget _buildFixedAppBar() {
    return AppBar(
      // backgroundColor: Colors.white,
      surfaceTintColor: Colors.white,
      elevation: 2,
      // 增加阴影，区分导航栏与内容区
      toolbarHeight: 80,
      // 匹配原导航栏高度
      titleSpacing: 0,
      title: Container(
        color: Colors.white,
        padding: EdgeInsets.only(
          left: 50,
          right: 50,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              alignment: Alignment.center,
              width: 50,
              color: Colors.green,
              height: 50,
              child: Text(
                "LOGO",
                style: TextStyle(fontSize: 18),
              ),
            ),
            SizedBox(
              width: 10,
            ),
            Container(
              alignment: Alignment.centerLeft,
              height: 80,
              child: ListView.builder(
                shrinkWrap: true,
                scrollDirection: Axis.horizontal,
                physics: NeverScrollableScrollPhysics(),
                itemBuilder: (context, index) {
                  NavbarItem item = controller.navbarItems[index];
                  return Container(
                    child: MouseRegion(
                      onEnter: (_) {
                        if (item.subItems?.isNotEmpty == true) {
                          controller.currentMenuIndex = index;
                          controller.showRightMenu = true;
                          controller.update();
                        }
                      },
                      onExit: (_) =>
                          setState(() => controller.showRightMenu = false),
                      // 鼠标在文本区域内移动时触发
                      onHover: (event) {
                        // print("=====onHover==");
                      },

                      // 鼠标指针样式（可选）
                      // cursor: SystemMouseCursors.move,
                      // cursor: SystemMouseCursors.click,
                      child: GestureDetector(
                        onTap: () {
                          controller.currentIndex = item.index;
                          controller.currentNavIndex = index;
                          controller.currentSubIndex = -1;
                          controller.update();
                        },
                        child: Row(
                          children: [
                            Container(
                              margin: EdgeInsets.only(
                                left: 20,
                              ),
                              alignment: Alignment.center,
                              child: Text(
                                item.title,
                                style: TextStyle(
                                  color: controller.currentNavIndex == index
                                      ? Colors.indigoAccent
                                      : Color(0xFF666666),
                                  fontSize: 16,
                                  fontWeight:
                                      controller.currentNavIndex == index
                                          ? FontWeight.bold
                                          : FontWeight.w400,
                                ),
                              ),
                            ),
                            if (item.subItems?.isNotEmpty == true)
                              Icon(controller.showRightMenu == false
                                  ? Icons.keyboard_arrow_down
                                  : Icons.keyboard_arrow_up),
                          ],
                        ),
                      ),
                    ),
                  );
                },
                itemCount: controller.navbarItems.length,
              ),
            ),
            Spacer(),
            // 搜索框（文档4）
            _buildSearchBar(),
            Container(
              alignment: Alignment.center,
              height: 40,
              width: 100,
              decoration: BoxDecoration(
                color: Colors.indigoAccent.shade200,
                borderRadius: BorderRadius.circular(8),
              ),
              child: TextButton(
                onPressed: () {},
                child: const Text(
                  "登录/注册",
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.w600),
                ),
              ),
            ),
          ],
        ),
      ),

      // title: Container(
      //   width: double.infinity,
      //   padding: EdgeInsets.symmetric(horizontal: 50),
      //   child: Row(
      //     children: [
      //       // LOGO
      //       Container(
      //         alignment: Alignment.center,
      //         width: 50,
      //         color: Colors.green,
      //         height: 50,
      //         child: Text("LOGO", style: TextStyle(color: Colors.white)),
      //       ),
      //       const SizedBox(width: 30),
      //       // 导航项（与TabController联动）
      //       ...["系统门户", "赋能平台", "新闻资讯", "领导关怀", "服务能力", "双创政策"]
      //           .asMap()
      //           .entries
      //           .map((entry) {
      //         int index = entry.key;
      //         String title = entry.value;
      //         return GestureDetector(
      //           onTap: () {
      //             // 点击导航项，切换TabController索引
      //             // _tabController.animateTo(index);
      //           },
      //           child: Padding(
      //             padding:
      //                 const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
      //             child: Text(
      //               title,
      //               style: TextStyle(
      //                 color: _currentIndex == index
      //                     ? Colors.indigoAccent
      //                     : Color(0xFF666666),
      //                 fontSize: 16,
      //                 fontWeight: _currentIndex == index
      //                     ? FontWeight.bold
      //                     : FontWeight.w400,
      //               ),
      //             ),
      //           ),
      //         );
      //       }).toList(),
      //       const Spacer(),
      //       // 搜索框
      //       // _buildSearchBar(),
      //       const SizedBox(width: 20),
      //       // 登录/注册按钮
      //       Container(
      //         alignment: Alignment.center,
      //         height: 40,
      //         width: 120,
      //         decoration: BoxDecoration(
      //           color: Colors.indigoAccent.shade200,
      //           borderRadius: BorderRadius.circular(8),
      //         ),
      //         child: TextButton(
      //           onPressed: () {},
      //           child: const Text(
      //             "登录/注册",
      //             style: TextStyle(
      //                 color: Colors.white,
      //                 fontSize: 14,
      //                 fontWeight: FontWeight.w600),
      //           ),
      //         ),
      //       ),
      //     ],
      //   ),
      // ),
    );
  }

  /// 搜索框（原代码迁移，优化样式）
  Widget _buildSearchBar() {
    return Container(
      width: 240,
      margin: EdgeInsets.only(right: 20),
      // padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
      color: Colors.white,
      child: TextField(
        decoration: InputDecoration(
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.grey, width: 1.0), // 边框颜色+宽度
            borderRadius: BorderRadius.circular(8), // 圆角（必填，否则是直角）
          ),
          hintText: "搜索...",
          hintStyle: const TextStyle(fontSize: 16, color: Color(0xFF999999)),
          prefixIcon:
              const Icon(Icons.search, color: Color(0xFF999999), size: 22),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(4),
            borderSide: BorderSide(color: Colors.grey, width: 1.0),
          ),
          contentPadding: const EdgeInsets.symmetric(vertical: 8),
          isDense: true,
        ),
      ),
    );
  }
}
